package com.yanyuan.mybaits.config;

import com.yanyuan.mybaits.config.xml.Command;
import com.yanyuan.mybaits.config.xml.Mapper;
import com.yanyuan.mybaits.config.xml.XmlBuilder;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description sqlSession工厂类
 * @Author yanyuan
 * @Date 16:06 2020/3/18
 * @Version 1.0
 **/
@Slf4j
public class SqlSessionFactory {

    static MapperRegistry mapperRegistry = new MapperRegistry();

    static Map<Method, Command> methodCache = new ConcurrentHashMap<>();

    static {
        build();
    }

    public static void build(){
        try {
            XmlBuilder xmlBuilder = new XmlBuilder();
            List<Mapper> mapperList = xmlBuilder.build();
            for (Mapper mapper : mapperList){
                Class<?> mapperInterface = Class.forName(mapper.getNamespace());
                for (Method method : mapperInterface.getMethods()){
                    log.info("method name {} ", method.getName());
                    for(Command command: mapper.getCommands()){
                        if(method.getName().equals(command.getId())){
                            methodCache.put(method, command);
                        }
                    }
                }
                mapperRegistry.addMapper(mapperInterface, methodCache);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession createSqlSession(){
        return new SqlSession(mapperRegistry);
    }
}
